package com.sofa.shark.file.remotefile.impl;

import com.alipay.sofa.rpc.common.RpcConstants;
import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.alipay.sofa.runtime.api.annotation.SofaServiceBinding;
import com.sofa.shark.common.core.enums.ExceptionEnums;
import com.sofa.shark.common.core.exception.BusinessException;
import com.sofa.shark.file.config.RemoteFileProperties;
import com.sofa.shark.file.entity.FileInfoBO;
import com.sofa.shark.file.entity.FileServerResponse;
import com.sofa.shark.file.enums.FileUploadSceneType;
import com.sofa.shark.file.remotefile.FileService;
import com.sofa.shark.file.remotefile.RemoteFileServerSevice;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tonyp
 */
@AllArgsConstructor
@ConditionalOnWebApplication
@Component
@SofaService(interfaceType = FileService.class,bindings = {@SofaServiceBinding(bindingType = RpcConstants.PROTOCOL_TYPE_BOLT)})
public class FileServiceImpl implements FileService {

    private final RemoteFileServerSevice remoteFileServerSevice;
    private final RemoteFileProperties remoteFileProperties;

    @Override
    public FileServerResponse<FileInfoBO> upload(File file, String path, FileUploadSceneType sceneType) {
        FileServerResponse<FileInfoBO> fileServerResponse;
        if (StringUtils.isBlank(sceneType.name())) {
            sceneType = FileUploadSceneType.DEFAULT;
        }
        if (StringUtils.isBlank(path)) {
            path = "default";
        }
        Map<String, Object> maps = new HashMap<>();
        maps.put("file", file);
        maps.put("scene", sceneType.name());
        maps.put("path", path);
        maps.put("output", "json");
        try {
            fileServerResponse = remoteFileServerSevice.upload(remoteFileProperties.getGroup(), maps);
        } catch (Exception ex) {
            throw new BusinessException(ExceptionEnums.UPLOAD_FILE_ERROR);
        } finally {
            file.delete();
        }
        return fileServerResponse;
    }
}
